const {
    logger,
    sleep,
    tiPost,
    saveScreenshot,
    checkCaptcha,
    SendSms,
    httpGet,
} = require('./util');

//加购物车
exports.addCart = async (page, serial) => {
    let orderedNum = 0;

    try {
        //如果货币不是CNY，切换，否则会影响加购物车
        //await chooseLangAndCountry(page);

        //库存和最大购买数量
        logger('获取商品库存数量');
        const stockUrl = 'https://www.ti.com.cn/storeservices/cart/opninventory?opn='+encodeURIComponent(serial);
        const res = JSON.parse(await httpGet(stockUrl));
        const stock = res.inventory;

        logger('加载快速加购物车页');
        const quickUrl = 'https://www.ti.com.cn/zh-cn/ordering-resources/buying-tools/quick-add-to-cart.html';
        await page.goto(quickUrl);
        await page.waitForSelector('.ti-quick-add-to-cart-worksheet-actions');
        await page.waitForTimeout(5000);
        await page.click('.ti-quick-add-to-cart-worksheet-actions');
        await page.waitForTimeout(30000);

        if (stock > 0) {
            //不能超过9999件
            const addNum = Math.min(stock, 9999);
            logger('将'+addNum+'加入购物车');

            // await page.evaluate((opnId, addNum) => {
            //     fetch('https://www.ti.com.cn/occservices/v2/ti/addtocart', {
            //         method:'POST',
            //         headers:{
            //             'Content-Type': 'application/json'
            //         },
            //         body:'{"cartRequestList":[{"opnId":"'+opnId+'","quantity":'+addNum+',"packageOption":null,"tiAddtoCartSource":"ti.com-quickcart"}],"currency":"CNY"}'
            //     });
            // }, serial, addNum);
            // await sleep(10000);

            //直接请求，不依赖页面，增加成功率
            try {
                const cookies = await page.cookies();
                const cookieArr = [];
                cookies.forEach(json => {
                    const { name, value } = json;
                    if (name == 'ti_rid') console.log('ti_rid', value);
                    cookieArr.push(name + '=' + value + ';');
                });
                let cookieStr = cookieArr.join(' ');
                cookieStr = cookieStr.substr(0, cookieStr.length - 1);
                //console.log('cookieStr', cookieStr);
                const url = 'https://www.ti.com.cn/occservices/v2/ti/addtocart';
                const data = '{"cartRequestList":[{"opnId":"TAS5548DCA","quantity":100,"packageOption":null,"tiAddtoCartSource":"ti.com-quickcart"}],"currency":"CNY"}';
                const referer = 'https://www.ti.com.cn/ordering-resources/buying-tools/quick-add-to-cart.html';
                const ret = await tiPost(url, data, cookieStr, referer);
                console.log('ret', ret);
            } catch(e) {
                logger('加购物车出错AA', page.url());
            }
            orderedNum++;
            await sleep(1800000);
        }
    } catch(e) {
        logger('加购物车出错', page.url(), e);
        await sleep(30000);
        await saveScreenshot(page, 'add_cart');
        await checkCaptcha(page);
        SendSms({
            TemplateId: '1169784',
            TemplateParamSet:[
                serial, '代码异常'
            ]
        }, 'dev');
    }

    return orderedNum;
}

const chooseLangAndCountry = async page => {
    try {
        await page.waitForSelector('.mod-currency', {
            timeout:60000
        });
        await page.waitForTimeout(3000);

        //语言
        const lang = await page.evaluate(() => {
            return document.querySelector('ti-header-language-selection').shadowRoot.querySelector('ti-dropdown-panel .ti-header-language-selection-trigger span').innerText;
        });
        if (lang != '中文') {
            logger('语言选择中文');
            await page.evaluateHandle(() => {
                document.querySelector('ti-header-language-selection').shadowRoot.querySelector('ti-dropdown-panel .ti-header-language-selection-trigger').click();
            });
            await page.waitForTimeout(1000);
            await page.evaluateHandle(() => {
                document.querySelector('ti-header-language-selection').shadowRoot.querySelector('ti-dropdown-panel li[data-value="zh-CN"] a').click();
            });
            await page.waitForTimeout(8000);
        }

        //配送区域
        const shipto = await page.evaluate(() => {
            return document.querySelector('ti-header-ship-to-selection').shadowRoot.querySelector('ti-dropdown-panel .ti-header-ship-to-selection-trigger span').innerText.toLowerCase();
        });
        if (shipto != 'china') {
            logger('区域选择中国');
            await page.evaluateHandle(() => {
                document.querySelector("ti-header-ship-to-selection").shadowRoot.querySelector("ti-dropdown-panel").shadowRoot.querySelector(".ti-dropdown-panel-trigger").click();
            });
            await page.waitForTimeout(1000);
            await page.evaluateHandle(() => {
                document.querySelector('ti-header-ship-to-selection').shadowRoot.querySelector('ti-dropdown-panel li[data-value="CN"] a').click();
            });
        }

        await page.waitForTimeout(1000);
    } catch(e) {

    }
}


